import React, { Component } from 'react'
//路由传参
import {withRouter} from "react-router-dom"
import {Toast,PickerView, WhiteSpace,Modal, Button, WingBlank,Picker,List,DatePicker,ImagePicker,NoticeBar

} from "antd-mobile"
import { Upload, message } from 'antd';
import OrderXj from '../../assets/img/order-xj.png'
import "./index.scss"
import SetRight from '../../assets/img/setRight.jpg'
import Axios from 'axios'
import { district, provinceLite } from 'antd-mobile-demo-data';
import { BASE_URL } from '../../utils/requestPath';
import requestAxios from '../../utils/myaxios'
import Nv from '../../assets/img/my_nv.png'
import OrderStart from '../../assets/img/11.png'
import OrderError from '../../assets/img/orderError.png'
const uploadImage = BASE_URL+"/uploadPictures"
const prompt = Modal.prompt;
const alert = Modal.alert;
const districtList = [
    {
        label:"男",
        value:"男"
    },
    {
        label:"女",
        value:"女"
    },
]
const season = [
    {
        label:"男",
        value:"男"
    },
    {
        label:"女",
        value:"女"
    },
]

const data = [{
    url: 'https://zos.alipayobjects.com/rmsportal/PZUUCKTRIHWiZSY.jpeg',
    id: '2121',
  }];

//图片
function beforeUpload(file) {
    console.log("----------------------------------------------------------------")
    console.log(file)
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 5; //file.size / 1024 / 1024 < 2 小于2M  
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

class Index extends Component {

    state = {
        reSet:"<",
        rightSet:"＞",
        headerImg:"",
        userName:"",
        paypalAccount:"",
        passWord:"",
        address:"",
        telephone:"",
        userGender:"",
        value:null,
        date:"",
        requestUserInfo:{},
        //userId:userInfoIns.id,
        files: data,
        multiple: false,
        userInfoIns:{},
        countColor:"",
        countIns:0,
        orderPageStart:false
    }

    componentDidMount(){
        document.title="完善信息"
        const userInfoNew = localStorage.getItem("userInfoIns")
        const userInfoIns = JSON.parse(userInfoNew) || {};
        this.setState({
            userInfoIns:userInfoIns
        })
       
        this.reSetGetList()
        console.log(localStorage.getItem("token"))
        console.log(userInfoIns)

        this.countInformation()


    }

    handleClick = (params) => {
        this.props.history.push("/searchCenter");
    }
    
    escOnClick=()=>{
        this.props.history.goBack()
    }

    //headerImage
    headerImageClick = (e)=>{
        console.log(e)
        const {headerImg} = this.state;
        const user = {headerImg}
        
       // this.myInformationRequest(user)
    }

    // axios request new 
    myInformationRequest=async(userInfo)=>{
        const id = this.state.userInfoIns.id;
        userInfo.id = id;
        await requestAxios.put(BASE_URL+"/api/user/update",userInfo).then(res=>{
            if(res.data === 1){
                Toast.loading('Loading...', 1, () => {
                    console.log('Load complete !!!');
                  });
            }
        })
        
        await this.reSetGetList()
        await this.countInformation()
    }

    onChange = (value) => {
        console.log(value);
        this.setState({
          value,
        });
      }
    onScrollChange = (value) => {
        console.log(value);
    }

    generOnChange=(e)=>{
        console.log(e)
    }  

    districtOnChange=(e)=>{
      console.log(e)

      this.setState({
          userGender:e
      })
      
      let userGender = "";

      if(e[0] === "男"){
          userGender = 1
      }else{
          userGender = 2
      }
      const userInfo = {userGender};
      this.myInformationRequest(userInfo)

      //console.log(this.state.userGender)
    }

    reSetGetList=async()=>{
        const userInfoIns = localStorage.getItem("userInfoIns");
        const userInfo = JSON.parse(userInfoIns) || {}

        //debugger
        await requestAxios.get(BASE_URL+"/api/user/getid/"+userInfo.id).then(res=>{
            if(res.data !== undefined){
                this.setState({
                    requestUserInfo:res.data
                })
            }
            localStorage.setItem("userInfoIns",JSON.stringify(res.data))
        })
    }


    dataOnChange = (data)=>{

        //console.log(data)
        var d = new Date(data); 
        d=d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds(); 
        // var s=new Date(stime).getTime();
        // var d=new Date(etime).getTime();
        console.log(d)
        console.log(new Date(data).getTime())

        const dateOfBirth = new Date(data).getTime()
        const userInfo = {dateOfBirth}
        //修改时间
        this.myInformationRequest(userInfo);

    }

    // 统计
    countInformation=()=>{
        const userInfoIns = localStorage.getItem("userInfoIns")
        const userInfo = JSON.parse(userInfoIns) || {}
        var count = 0;
        //debugger
        if(userInfo.dateOfBirth != null && userInfo.dateOfBirth){
            count += 12.5
        }
        if(userInfo.goodsAddress != null && userInfo.goodsAddress){
            count += 12.5
        }
        if(userInfo.headerImg != null && userInfo.headerImg){
            count += 12.5
        }
        if(userInfo.paypalAccount != null && userInfo.paypalAccount){
            count += 12.5
        }
        if(userInfo.telephone != null && userInfo.telephone){
            count += 12.5
        }
        if(userInfo.userGender){    
            count += 12.5
        }
        if(userInfo.userName != null && userInfo.userName){
            count += 12.5
        }
        if(userInfo.zgEmail != null && userInfo.zgEmail){
            count += 12.5
        }

        //debugger
        if(this.state.requestUserInfo.informationPerfect === 0 && count >= 90){
            //request........ integral += 

            console.log("++++++++integral")
            const id = userInfo.id;
            const type = 3;
            const userInfoInst = {id,type};
            //如果注册成功,增加积分.....  
            requestAxios.post(BASE_URL+"/api/order/add/start",userInfoInst).then(res=>{
                console.log(res)
                if(res.data.flag){
                   setTimeout(()=>{
                      this.setState({
                          orderPageStart:true
                      })
                   },1000)
                }
            })

        }

        if(count >= 80){
            this.setState({
                countColor:"#7CFC00"
            })
        }else if(count >= 75){
            this.setState({
                countColor:"#FFD700"
            })
        }else if(count >= 37.5){
            this.setState({
                countColor:""
            })
        }else{
            this.setState({
                countColor:""
            })
        }

        this.setState({
            countIns:count
        })

        console.log(count)
    }


    handleChange = info => {
        console.log(info)
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
        //   getBase64(info.file.originFileObj, imageUrl =>
        //     this.setState({
        //       imageUrl,
        //       loading: false,
        //     }),
        //   );
            console.log(info.file.response)
            const headerImg = "http://"+info.file.response
            const userInfo = {headerImg};
            this.myInformationRequest(userInfo);
            // let {imagesList} = this.state;
            // let iamgesListAll = imagesList
            // iamgesListAll.push(
            //     {
            //         time:parseInt(new Date().getTime()),
            //         url:"http://"+info.file.response
            //     }
            // )
            
            // this.setState({
            //     imagesList:iamgesListAll
            // })

            //console.log(iamgesListAll)
        }
      };

      escLoginClick=()=>{

        
      }

     
    successToast=()=>{
        Toast.success('保存成功!', 1);
    }

    //开心收下去使用
    lwOnClick = ()=>{
        this.setState({
            orderPageStart:false
        })
        // 跳转我的个人中心 navigator
        this.props.history.push("/navigator");
      }
  
    //关闭也是跳转 navigator
    orderErrorOnClick=()=>{
        this.setState({
            orderPageStart:false
        })
      this.props.history.push("/navigator");
    }



    render() {
        const {reSet,rightSet,requestUserInfo,files,imageUrl } = this.state
        const uploadButton = (
            <div style={{flexDirection:"column",alignItems:"center"}}>
              {/* {loading ? <LoadingOutlined /> : <PlusOutlined />} */}
              <img src={SetRight} style={{width:20,height:20}}></img>
              {/* <div style={{ marginTop: 8 ,fontWeight:"800"}}></div> */}
            </div>
          );
        return (
            <div className="main-myinformation">
               
                 {/* 头部,返回,评价 */}
                 <header className="main-myinformation-header">
                    <div className="main-myinformation-header-con" onClick={this.escOnClick}>
                        <span className="main-myinformation-header-con-span-one">{reSet}</span>
                        <span  className="main-myinformation-header-con-span-two">返回</span>
                    </div>
                    <h4>
                        アカウントと安全
                    </h4>
                </header>
                <section style={{width:"100%",height:27}}>
                <NoticeBar marqueeProps={{ loop: true, style: { padding: '0 7.5px' } }}>
                情報を完全にすると2000ポイントGET.......... &#39;情報を完全にすると2000ポイントGET..........
    </NoticeBar>
                </section>
                
                {/* 中间内容 */}
                <main className="main-myinformation-content">
                    
                    {/* 信息列表One */}
                    <div className="main-myinforation-list">
                        {/* headerimg */}
                        <section className="main-myinforation-list-header-img">
                            <h4 className="main-myinforation-list-header-left"> 
                            情報を完全にするとポイントGET
                            </h4>
                            <div className="main-myinforation-list-header-right" onClick={this.headerImageClick.bind(this,this.state.userInfoIns.headerImg)}>
                                <img src={requestUserInfo.headerImg?requestUserInfo.headerImg:Nv}>
                                </img>
                                {/* <img style={{width:21,height:21}} src={SetRight}></img> */}
                                {/* <h4>{SetRight}</h4> */}
                                    {/* <ImagePicker
                                        onChange={this.onChangeImg}
                                        onImageClick={(index, fs) => console.log(index, fs)}
                                        selectable={files.length < 2}
                                        multiple={this.state.multiple}
                                        style={{width:100,height:100,position:"absolute",bottom:-57,right:-61}}
                                        /> */}
                                        <Upload
                                        name="file"
                                        listType="picture-card"
                                        className="avatar-uploader"
                                        showUploadList={false}
                                        action={uploadImage}
                                        beforeUpload={beforeUpload}
                                        onChange={this.handleChange}
                                        style={{width:100,height:100,position:"absolute",bottom:-57,right:-61}}
                                    >
                                        {/* {this.state.imagesList.length >= 2 ? <img src={OrderXj} style={{ width: '100%' }} alt="avatar" ></img> : uploadButton} */}
                                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                            </div>
                        </section>
                        {/* nickName */}
                        <section style={{width:"100%",height:44,position:"relative",borderBottomColor:"none"}}>
                        <Picker
                                
                                extra={requestUserInfo.userName}
                                className="main-myinforation-list-header-paypal-account"
                                data={districtList} cols={1}
                                // {...getFieldProps('district3')}  
                                className="forss">
                                <List.Item arrow="horizontal">ユーザーID</List.Item>
                                </Picker>
                                <Button 
                                
                                style={{position:"absolute",width:"100%",background:"rgba(0,0,0,0)",height:"100%",zIndex:100,top:0}}
                                onClick={() => prompt('', 'defaultValue for prompt', [
                                { text: 'Cancel' },
                                { text: 'Submit', onPress: value => {
                                    const userName = value;
                                    const userInfo = {userName};
                                    // 发送请求
                                    this.myInformationRequest(userInfo)
                                } },
                                ], 'default', requestUserInfo.userName)}
                                ></Button>
                       </section>
                        {/* paypalAccount */}
                        <section style={{width:"100%",height:44,position:"relative",borderBottomColor:"none"}}>
                        <Picker
                                
                                extra={requestUserInfo.paypalAccount}
                                className="main-myinforation-list-header-paypal-account"
                                data={districtList} cols={1}
                                // {...getFieldProps('district3')}
                                className="forss">
                                <List.Item arrow="horizontal">paypalアカウント</List.Item>
                                </Picker>
                                <Button 
                                style={{position:"absolute",width:"100%",background:"rgba(0,0,0,0)",height:"100%",zIndex:100,top:0}}
                                onClick={() => prompt('', 'defaultValue for prompt', [
                                { text: 'Cancel' },
                                { text: 'Submit', onPress: value => {
                                    const paypalAccount = value;
                                    const userInfo = {paypalAccount};
                                    // 发送请求
                                    this.myInformationRequest(userInfo)
                                } },
                                ], 'default', requestUserInfo.paypalAccount)}
                                ></Button>
                       </section>
                    </div>

                    {/* 信息列表Two */}
                    <div className="main-myinforation-list-two">
                    <section style={{width:"100%",height:44,position:"relative",borderBottomColor:"none"}}>
                        <Picker
                                
                                //value={this.state.userGender}
                                extra="......"
                                className="main-myinforation-list-header-paypal-account"
                                data={districtList} cols={1}
                                className="forss">
                                <List.Item arrow="horizontal">パスワード</List.Item>
                                </Picker>
                                <Button 
                                    style={{position:"absolute",width:"100%",background:"rgba(0,0,0,0)",height:"100%",zIndex:100,top:0}}
                                    onClick={() => prompt(
                                    'Password',
                                    'set new PassWord',
                                     password => {
                                        
                                        {
                                            const passWord = password;
                                            const userInfo = {passWord};
                                            // 发送请求
                                            this.myInformationRequest(userInfo)
                                        }
                                        
                                     },
                                    'secure-text',
                                    )}
                                    ></Button>
                       </section>
                        <section style={{width:"100%",height:44,position:"relative",borderBottomColor:"none"}}>
                        <Picker
                                
                                //value={this.state.userGender}
                                extra={requestUserInfo.zgEmail}
                                className="main-myinforation-list-header-paypal-account"
                                data={districtList} cols={1}
                                // {...getFieldProps('district3')}
                                className="forss">
                                <List.Item arrow="horizontal">邮箱</List.Item>
                                </Picker>
                                <Button 
                                style={{position:"absolute",width:"100%",background:"rgba(0,0,0,0)",height:"100%",zIndex:100,top:0}}
                                onClick={() => prompt('', 'defaultValue for prompt', [
                                { text: 'Cancel' },
                                { text: 'Submit', onPress: value => {

                                    const zgEmail = value;
                                    const userInfo = {zgEmail};
                                    // 发送请求
                                    this.myInformationRequest(userInfo)

                                } },
                                ], 'default', requestUserInfo.zgEmail)}
                                ></Button>
                       </section>
                        <section style={{width:"100%",height:44,position:"relative",borderBottomColor:"none"}}>
                        <Picker
                                //value={this.state.userGender}
                                extra={requestUserInfo.userMansion + requestUserInfo.userCity + requestUserInfo.userStreet || "..."}
                                className="main-myinforation-list-header-paypal-account"
                                data={districtList} cols={1}
                                // {...getFieldProps('district3')}
                                className="forss">
                                <List.Item arrow="horizontal">详细地址</List.Item>
                                </Picker>
                                <Button 
                                style={{position:"absolute",width:"100%",background:"rgba(0,0,0,0)",height:"100%",zIndex:100,top:0}}
                                onClick={() => prompt('', 'defaultValue for prompt', [
                                { text: 'Cancel' },
                                { text: 'Submit', onPress: value => {
                                    
                                    {
                                        const goodsAddress = value;
                                        const userInfo = {goodsAddress};
                                        // 发送请求
                                        this.myInformationRequest(userInfo)
                                    }

                                } },
                                ], 'default', requestUserInfo.userMansion + requestUserInfo.userCity + requestUserInfo.userStreet)}
                                ></Button>
                       </section>
                    </div>

                     {/* 信息列表Three */}
                     <div className="main-myinforation-list-three">
                     <section style={{width:"100%",height:44,position:"relative"}}>
                       <Picker
                            
                            extra={requestUserInfo.telephone}
                            className="main-myinforation-list-header-paypal-account"
                            data={districtList} cols={1}
                            className="forss">
                            <List.Item arrow="horizontal">电话</List.Item>
                            </Picker>
                            <Button 
                            style={{position:"absolute",width:"100%",background:"rgba(0,0,0,0)",height:"100%",zIndex:100,top:0}}
                            onClick={() => prompt('', 'defaultValue for prompt', [
                            { text: 'Cancel' },
                            { text: 'Submit', onPress: value => 
                                {
                                    const telephone = value;
                                    const userInfo = {telephone};
                                    // 发送请求
                                    this.myInformationRequest(userInfo)
                                } },
                            ], 'default', requestUserInfo.telephone)}
                            ></Button>
                       </section>
                       <section>
                       <DatePicker
                            minDate={new Date(1970,1,1,0,0,0)}
                            className="main-myinforation-list-header-paypal-account"
                            mode="date"
                            title="Select Date"
                            extra="请选择日期"
                            value={requestUserInfo.dateOfBirth !== null?new Date(parseInt(requestUserInfo.dateOfBirth)):""}
                            onChange={this.dataOnChange}
                            >
                        <List.Item arrow="horizontal">出生年月</List.Item>
                        </DatePicker>
                       </section>
                 
                       <section>
                       <Picker
                            onChange={this.districtOnChange}
                            //value={this.state.userGender}
                            extra={requestUserInfo.userGender === 1?"男":"女"}
                            className="main-myinforation-list-header-paypal-account"
                            data={districtList} cols={1}
                            className="forss">
                            <List.Item arrow="horizontal">性别</List.Item>
                            </Picker>
                       </section>
                    </div>

                    
                </main>
                    
                    <section className="main-myinforation-footerOne" style={{position:"relative"}}>
                        <Button 
                        className="main-myinforation-footer-successbutton"
                        type="primary" onClick={this.successToast}>保存</Button>
                        <div className="main-myinforation-good-dug" style={{position:"absolute",background:`${this.state.countColor}`}}>
                            <h4>{this.state.countIns}%</h4>
                            <h5>信息完善度</h5>
                        </div>
                    </section>
                    {/* 确定 */}
                    <footer className="main-myinforation-footer">
                    
                    <Button
                    className="main-myinforation-footer-escbutton"
                    onClick={() =>
                        alert('EscLogin', 'Are you sure???', [
                        { text: 'Cancel', onPress: () => console.log('cancel') },
                        {
                            text: 'Ok',
                            onPress: () =>{
                                localStorage.removeItem("userInfoIns")
                                localStorage.removeItem("token")
                                localStorage.removeItem("jumpStartThree")
                                localStorage.removeItem("jumpStart")
                                localStorage.removeItem("jumpStartTwoIns")
                                this.props.history.push("/login")
                            }
                            },
                        ])
                    }
                    >
                    退出登陆
                    </Button>
                    </footer>
              {this.state.orderPageStart?<div style={{position:"absolute",width:"100%",
                height:"100vh",background:"#fff",paddingTop:70,top:0,zIndex:1000,
                display:"flex",flexDirection:"column",
                alignItems:"center",justifyContent:"space-around"}}>
                    <div style={{height:36,width:240,background:"rgb(32, 32, 32)",
                    borderRadius:5,display:"flex",flexDirection:"row",
                    justifyContent:"center",alignItems:"center",}}>
                        <h4 style={{width:182,height:26,
                            alignItems:"center",
                            lineHeight:2,
                            color:"rgb(245, 245, 245)",border:"1px solid rgb(250, 250, 250)",
                            borderRadius:10,textAlign:"center",}}>信息完善礼包</h4>
                    </div>       
                    <div style={{position:"relative",width:"100%",height:380,display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center"}}>
                        <div style={{position:"absolute",display:"flex",flexDirection:"column",alignItems:"center",height:380,width:"100%"}}>
                            <h2 style={{color:"rgb(230, 60, 57)",lineHeight:2,marginTop:70,fontSize:18,}}>完善信息</h2>
                            <h3 style={{color:"rgb(230, 60, 57)",lineHeight:2,marginTop:5}}><span style={{fontSize:28,letterSpacing:2,fontWeight:"bold"}}>2000</span>积分</h3>
                            <h4 style={{color:"rgb(230, 60, 57)",lineHeight:2,marginTop:5}}>即200日元</h4>
                            <h5 style={{color:"rgb(230, 60, 57)",
                            lineHeight:1.9,marginTop:68,fontSize:18,
                            height:36,width:84,background:"rgb(250, 200, 13)",borderRadius:8,textAlign:"center"}}>用户专项</h5>
                        </div>    
                        <img src={OrderStart}>
                            
                        </img>
                    </div>    
                    
                    <h3 onClick={this.lwOnClick} style={{width:217,height:36,background:"rgb(229, 60, 57)",borderRadius:14,lineHeight:2.8,color:"#fff",textAlign:"center"}}>
                        开心收下 去使用
                    </h3> 

                    <div onClick={this.orderErrorOnClick} style={{width:45,height:45,borderRadius:45,background:"#fff",border:"#000",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center"}}>
                        <img style={{width:40,height:40}} src={OrderError}></img>
                    </div>       
                </div>:""      
            }
                   
            </div>
        )
    }
}
export default withRouter(Index)
